import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { View, Image, Text, Button } from '@tarojs/components'
import { AtButton, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtIcon, AtForm } from 'taro-ui'
import { OrderDto } from 'src/services/order/dto/orderDto'
import { observer, inject } from '@tarojs/mobx'
import Stores from "../../stores/storeIdentifier"
import ProductStore from '../../stores/productStore'
import CartStore from '../../stores/cartStore'
import AuthenticationStore from '../../stores/authenticationStore'
import OrderStore from '../../stores/orderStore'
import WxOpenStore from '../../stores/wxOpenStore';

import './share.scss'
import WxOpenLoginModel from '../../models/login/wxOpenLoginModel';
import { JsApiReturnModel } from '../../services/dto/jsApiReturnModel'
import { PayResultModel } from '../../services/dto/payResultModel';
import { UserShippingAddressDto } from '../../services/cart/dto/userShippingAddressDto';

export interface IShareProps {
    productStore: ProductStore,
    cartStore: CartStore,
    authenticationStore: AuthenticationStore,
    orderStore: OrderStore,
    wxOpenStore: WxOpenStore
}

@inject(Stores.ProductStore, Stores.AuthenticationStore, Stores.CartStore, Stores.OrderStore, Stores.WxOpenStore)
@observer
class Share extends Component<IShareProps> {
    config: Config = {
        backgroundColor: '#c80d0d',
        navigationBarTitleText: '您收到礼物'
    }
    jsApiModel: JsApiReturnModel
    payResult: PayResultModel
    isLoading: boolean = true
    state = {
        isOpened: false
    };
    order: OrderDto
    defaultAddress: UserShippingAddressDto
    accessToken: string
    wxOpenLoginModel: WxOpenLoginModel = new WxOpenLoginModel();
    async componentWillMount() {
        if (!Taro.getStorageSync('access_token')) {
            this.setState({ isOpened: true });
        }
        await this.getOrder()
    }

    async componentDidShow() {
        var pages = getCurrentPages()

        if (pages.length >= 2) {
            let prevPage = pages[pages.length - 2]
            prevPage.setData({
                orderFlag: true
            })
        }
        if (pages) {
            let prev = pages[pages.length - 1]
            if (prev.data.defaultAddress) {
                this.defaultAddress = prev.data.defaultAddress
                await this.changeOrderAddress()
            }
        }
        this.setState({})
    }

    async changeOrderAddress() {
        await this.props.orderStore.changeOrderUserShippingAddress(this.defaultAddress.id, this.$router.params.id)
        this.order.receiptUserName = this.defaultAddress.receiptUserName
        this.order.mobilephone = this.defaultAddress.mobilephone
        this.order.areaCodeDisplayName = this.defaultAddress.areaCodeDisplayName
        this.order.address = this.defaultAddress.address
        this.setState({})
    }

    async getOrder() {
        await this.props.orderStore.getOrderDetail(this.$router.params.id)
        this.order = this.props.orderStore.order
        this.setState({})
    }

    disabledChange() {

    }

    async formSubmit(e) {
        if (!Taro.getStorageSync('access_token')) {
            this.setState({ isOpened: true });
        }
        else {
            //type==1 付款  type==0，确认是否同意收礼
            if (this.$router.params.type == 1) {
                await this.onGetPay();
            }
            else {
                await this.confirmOrder()
            }
            await this.props.wxOpenStore.createFormIds([{ formId: e.detail.formId, formIdType: 0 }])
        }
    }

    onGetPay = async () => {

        await this.props.orderStore.getApiPay(this.$router.params.id)
        this.jsApiModel = this.props.orderStore.jsApiModel

        if (this.jsApiModel) {
            var _package = this.jsApiModel.package as string
            var _prepay_id = _package.replace('prepay_id=', '')
            await this.props.wxOpenStore.createFormIds([{ formId: _prepay_id, formIdType: 1 }])
            let this_ = this
            Taro.requestPayment({
                timeStamp: this.jsApiModel.timestamp,
                nonceStr: this.jsApiModel.nonceStr,
                package: this.jsApiModel.package,
                signType: this.jsApiModel.signType,
                paySign: this.jsApiModel.paySign,
                async success(res) {
                    await this_.getPayStatus(_prepay_id)
                },
            }).then((res) => {

            })
        }
    }

    async getPayStatus(prepay_id: string) {
        if (this.isLoading) {
            await this.props.orderStore.getPayStatus(this.$router.params.id)
            this.payResult = this.props.orderStore.payResult
            if (this.payResult.isSuccess) {
                this.isLoading = false
                this.setState({}, async () => {
                    await this.getPayStatus(prepay_id)
                })
            }
        }
    }

    async confirmOrder() {
        if (this.$router.params.type == 0) {
            await this.props.orderStore.confirmOrder(this.$router.params.id)
                .then(async () => {
                    this.order.isConfirmed = true
                })
        }
        this.setState({})
    }

    handleModalClose() {
        this.setState({ isOpened: false });
    }

    async login() {
        await this.props.authenticationStore!.wxOpenLogin(this.wxOpenLoginModel)
        this.accessToken = this.props.authenticationStore!.accessToken
    }

    gotoWxOpenLogin = async (e) => {
        console.log(e)
        this.setState({ isOpened: false });
        var that = this;
        if (!Taro.getStorageSync('access_token') && e.detail.userInfo) {
            Taro.login({
                async success(res) {
                    if (res.code) {
                        // 发起网络请求
                        that.wxOpenLoginModel.code = res.code;
                        that.wxOpenLoginModel.state = 'Csproj_wxOpen_Bind';
                        that.wxOpenLoginModel.returnUrl = '/pages/index/share?id=' + that.$router.params.id + '&type=' + that.$router.params.type
                        that.wxOpenLoginModel.encryptedData = e.detail.encryptedData;
                        that.wxOpenLoginModel.iv = e.detail.iv;
                        that.wxOpenLoginModel.rawData = e.detail.rawData;
                        that.wxOpenLoginModel.signature = e.detail.signature;
                        await that.login()
                    }
                }
            });
        }
    }

    async gotoAddrss(e) {
        await this.props.wxOpenStore.createFormIds([{ formId: e.detail.formId, formIdType: 0 }])
        Taro.navigateTo({ url: '/pages/profile/address/index?prev=order&ids=' + this.$router.params.ids })
    }

    render() {
        return (<View className='index-wrap'>
            {
                this.order && this.order.orderItems.length &&
                <View className='cart-box'>
                    {this.order.orderItems.map((item) => (
                        <View className='cart-cell'>
                            <View className='cart-hd'>
                                <Image mode='aspectFill' src={item.featuredImage} />
                            </View>
                            <View className='cart-bd'>
                                <View className='tit'>{item.productName}</View>
                                <View className='p'>{item.skuName}</View>
                                <View className='disc'>
                                    {this.$router.params.type == 1 && <Text>￥{item.finalUnitPrice}</Text>}
                                    <Text className='num'>x{item.quantity}</Text>
                                </View>
                            </View>
                        </View>
                    ))}
                </View>
            }
            {
                <View className='index-panel'>
                    {/*<View className='index-panel-header'>传达心意，写祝福语</View>*/}
                    <View className='index-panel-body'>
                        <View className='wish-wrap'>
                            {
                                this.order.remark &&
                                <View>{this.order.remark}</View>
                            }
                            {
                                !this.order.remark &&
                                <View>Ta什么也没写，该说的都在礼物里了^_^</View>
                            }
                        </View>
                    </View>
                </View>
            }
            {
                this.$router.params.type == 1 &&
                <View className='index-price'>
                    <Text className='sm'>￥</Text>
                    <Text className='price'>{this.order.finalPrice}</Text>
                </View>
            }


            <View className='order-address'>
                {
                    this.order && this.$router.params.type == 0 && this.order.receiptUserName &&
                    <View className='address-item ratina-bd bd-b'>
                        <View className='addr-hd'>
                            <Text className='name'>{this.order.receiptUserName}</Text>
                        </View>
                        <View className='addr-bd'>
                            <Text className='tel'>{this.order.mobilephone}</Text>
                            <Text className='addr-disc'>{this.order.areaCodeDisplayName}{this.order.address}</Text>
                        </View>
                    </View>
                }
            </View>
            <View className='index-btn-wrap'>
                {this.order && this.$router.params.type == 0 && !this.order.isConfirmed && !this.order.receiptUserName && (
                    <AtForm className='normal-form' reportSubmit={true} onSubmit={this.gotoAddrss.bind(this)}>
                        <View className='no-address'>
                            <AtButton type='primary' formType='submit'>立即原谅</AtButton>
                        </View>
                    </AtForm>
                )}

                {
                    this.order && this.$router.params.type == 0 && !this.order.isConfirmed && this.order.receiptUserName && (
                        <AtForm className='normal-form' reportSubmit={true} onSubmit={this.formSubmit.bind(this)}>
                            <AtButton type='primary' formType='submit'>确认</AtButton>
                        </AtForm>
                    )
                }
                {
                    this.order && this.$router.params.type == 1 && this.order.status == 0 && (
                        <AtForm className='normal-form' reportSubmit={true} onSubmit={this.formSubmit}>
                            <AtButton type='primary' formType='submit'>获得原谅</AtButton>
                        </AtForm>)
                }
            </View>

            <AtModal isOpened={this.state.isOpened}>
                <AtModalHeader>微信授权</AtModalHeader>
                <AtModalContent>
                    该页面申请获取您的用户资料（昵称、头像、地区及性别）
                </AtModalContent>
                <AtModalAction>
                    <Button onClick={this.handleModalClose}>拒绝</Button>
                    <Button openType='getUserInfo' onGetUserInfo={this.gotoWxOpenLogin}>允许</Button>
                </AtModalAction>
            </AtModal>
        </View>

        )
    }
}

export default Share
